<script lang="ts" setup>
import lodash from 'lodash'
import moment from 'moment'
import * as d3 from 'd3'
import { Tag } from 'vant'
import { OrderApi } from '~/api/OrderApi'
import PairsView from '~/components/common/PairsView.vue'
import SalesPie from '~/components/statistics/SalesPie.vue'
import { OrderModel } from '~/model'
import { pickDate } from '~/utils'

const route = useRoute()
const router = useRouter()
const day = ref(new Date())

// const orders = ref([] as OrderModel[])
// const ordersOfDay = computed(() => {
//   const sD = moment(day.value).format('YYYYMMDD')
//   return orders.value.filter((order) => {
//     return moment(order.date).format('YYYYMMDD') === sD
//   })
// })
const ordersOfDay = ref([] as OrderModel[])

interface NameQuantityAmount {
  name: string
  quantity: number
  amount: number
}
const itemSummaryOfDay = computed(() => {
  const orderItems = lodash.flatten(ordersOfDay.value.map(x => x.items))
  const groupedByName = lodash.groupBy(orderItems, x => x.material?.fullName)
  const res: NameQuantityAmount[] = []
  for (const name of Object.keys(groupedByName)) {
    res.push({
      name,
      quantity: groupedByName[name].map(x => x.quantity).reduce((y, x) => y + x, 0),
      amount: groupedByName[name].map(x => x.amount).reduce((y, x) => y + x, 0),
    })
  }
  res.sort((a, b) => b.amount - a.amount)

  return res
})

const taNoFareOfDay = computed(() => {
  return itemSummaryOfDay.value.map(x => x.amount).reduce((y, x) => y + x, 0)
})

const consumerSummaryOfDay = computed(() => {
  // const orderItems = lodash.flatten(ordersOfDay.value.map(x => x.items))
  const groupedByConsumer = lodash.groupBy(ordersOfDay.value, x => x.consumer!.name)
  const res: NameQuantityAmount[] = []
  for (const name of Object.keys(groupedByConsumer)) {
    res.push({
      name,
      quantity: groupedByConsumer[name].length,
      amount: groupedByConsumer[name].map(x => x.totalAmount()).reduce((y, x) => y + x, 0),
    })
  }
  res.sort((a, b) => b.amount - a.amount)

  return res
})

const taOfDay = computed(() => {
  return consumerSummaryOfDay.value.map(x => x.amount).reduce((y, x) => y + x, 0)
})

onMounted(() => {
  const a = route.query.date as string | undefined
  if (a) {
    day.value = new Date(a)
  }

  OrderApi.getPaged(1, 1000000, {
    date_start: moment(day.value).format('YYYY-MM-DD'),
    date_end: moment(day.value.valueOf() + 86400000).format('YYYY-MM-DD'),
  })
    .then((page) => {
      ordersOfDay.value = page.objects
    })
})

const tableOption = [
  '商品统计',
  '用户统计',
]
const activeTableOptionIndex = ref(0)

// const nixx = [1, 2]
function color1(param: string) {
  const domain = itemSummaryOfDay.value.map(x => x.name)
  return d3.scaleOrdinal()
    .domain(domain)
    .range(
      d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1),
        domain.length,
      ).reverse())(param)
}
function color2(param: string) {
  const domain = consumerSummaryOfDay.value.map(x => x.name)
  return d3.scaleOrdinal()
    .domain(domain)
    .range(
      d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1),
        domain.length,
      ).reverse())(param)
}

async function switchDate() {
  const res = await pickDate(day.value)
  router.replace(`${route.path}?date=${moment(res).format('YYYY-MM-DD')}`)
  setTimeout(() => {
    router.go(0)
  }, 50);
}
</script>

<template>
  <div p4>
    <PairsView
      :pairs="[
        ['日期', moment(day).format('YYYY-MM-DD'), switchDate],
      ]"
    />

    <div my2 flex>
      <Tag
        v-for="(item, index) in tableOption"
        :key="index"
        type="primary"
        size="large" mr2 flex-cc flex-1
        style="font-size: 1rem; line-height: 1.5rem; height: 3rem;"
        :plain="activeTableOptionIndex === index ? false : true"
        @click="activeTableOptionIndex = index"
      >
        {{ item }}
      </Tag>
    </div>

    <div paper of-hidden p0>
      <div v-if="activeTableOptionIndex === 0">
        <SalesPie m4 flex-cc flex-1 :data="itemSummaryOfDay.map(x => ({ name: x.name, value: x.amount }))" />

        <table v-if="itemSummaryOfDay" class="lx-table">
          <thead>
            <tr>
              <td />
              <td>商品</td>
              <td text-right>
                数量
              </td>
              <td>金额</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="line in itemSummaryOfDay" :key="line.name">
              <td>
                <div h-3 w-3 :style="{ backgroundColor: color1(line.name) }" />
              </td>
              <td>{{ line.name }}</td>
              <td text-right>
                {{ line.quantity }}
              </td>
              <td>{{ line.amount }}</td>
            </tr>
          </tbody>
        </table>
        <!--  -->
        <div text-size="3.5" flex lh-10 text-gray-9>
          <div w="250px" px2>
            货款总计(不计算运费)
          </div>
          <div flex-1 flex-grow-1 px3>
            {{ taNoFareOfDay }}
          </div>
        </div>
      </div>

      <div v-if="activeTableOptionIndex === 1">
        <SalesPie m4 flex-cc flex-1 :data="consumerSummaryOfDay.map(x => ({ name: x.name, value: x.amount }))" />

        <table v-if="consumerSummaryOfDay" class="lx-table">
          <thead>
            <tr>
              <td />
              <td>用户</td>
              <td text-right>
                订单数
              </td>
              <td>金额</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="line in consumerSummaryOfDay" :key="line.name">
              <td>
                <div h-3 w-3 :style="{ backgroundColor: color2(line.name) }" />
              </td>
              <td>{{ line.name }}</td>
              <td text-right>
                {{ line.quantity }}
              </td>
              <td>{{ line.amount }}</td>
            </tr>
          </tbody>
        </table>

        <div text-size="3.5" flex lh-10 text-gray-9>
          <div w="250px" px2>
            货款总计(含运费)
          </div>
          <div flex-1 flex-grow-1 px3>
            {{ taOfDay }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>

<route lang="yaml">
meta:
  title: 统计
</route>
